import path from 'node:path';
import { defineConfig, loadEnv, ConfigEnv, UserConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { createHtmlPlugin } from 'vite-plugin-html';

// 创建基础配置
const createBaseConfig = (dirname: string) => ({
  plugins: [
    vue({
      script: {
        defineModel: false,
        propsDestructure: false
      }
    }),
    vueJsx(),
    createHtmlPlugin({
      inject: {
        data: {
          title: 'admin - 微前端架构 (Element Plus)'
        }
      }
    })
  ],
  resolve: {
    alias: {
      '@': path.resolve(dirname, 'src'),
    },
  },
});

// 创建构建配置
const createBuildConfig = (name: string, entry: string, isProduction: boolean) => ({
  outDir: 'dist',
  sourcemap: !isProduction,
  minify: isProduction ? 'terser' as const : false,
  terserOptions: isProduction ? {
    compress: {
      drop_console: true,
      drop_debugger: true,
    },
  } : undefined,
  rollupOptions: {
    input: {
      [name]: entry,
    },
    output: {
      manualChunks: {
        'chunk-vue': ['vue', 'vue-router', 'pinia'],
        'chunk-element': ['element-plus', '@element-plus/icons-vue'],
        'chunk-qiankun': ['qiankun'],
      },
    },
  },
});

// 创建服务器配置
const createServerConfig = (port: number) => ({
  port,
  host: true,
  open: false,
  cors: true,
  strictPort: false,
  headers: {
    'Access-Control-Allow-Origin': '*'
  },
  proxy: {
    '/dev-api': {
      target: 'http://localhost:8080',
      changeOrigin: true,
      // 不重写路径，保留 /dev-api 前缀发送给后端
      rewrite: (path) => path,
      configure: (proxy, _options) => {
        proxy.on('proxyReq', (proxyReq, req, _res) => {
          console.log('[Proxy] 请求:', req.method, req.url, '->', proxyReq.path);
        });
      }
    }
  }
});

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '');

  const isProduction = mode === 'production';

  const config = {
    ...createBaseConfig(__dirname),
    server: createServerConfig(3000),
    define: {
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: false,
      'import.meta.env': JSON.stringify(env),
    },
    optimizeDeps: {
      include: ['vue', 'vue-router', 'element-plus', 'qiankun', 'pinia']
    },
  };

  if (isProduction) {
    // @ts-ignore - Vite版本兼容性问题
    return {
      ...config,
      build: createBuildConfig('microFrontendMain', './src/main.ts', true),
    };
  }

  // @ts-ignore - Vite版本兼容性问题
  return {
    ...config,
    base: '/',
    build: createBuildConfig('microFrontendMain', './src/main.ts', false),
  };
});
